<template>
  <div class="plan-page" style="padding: 20px">
    <el-row justify="space-between" align="middle" style="margin-bottom: 10px;">
      <el-col>
        <el-button type="primary" size="small" @click="addStrategy">新增策略</el-button>
        <el-button type="success" size="small" @click="exportExcel">导出 Excel</el-button>
      </el-col>
    </el-row>

    <el-table :data="filteredPlans" border stripe :default-sort="{ prop: 'energy', order: 'ascending' }"
      style="width: 100%">
      <el-table-column prop="enabled" label="启用" width="80">
        <template #default="{ row }">
          <el-switch v-model="row.enabled" />
        </template>
      </el-table-column>
      <el-table-column prop="energy" label="能源" width="80" sortable />
      <el-table-column prop="device" label="设备类型" width="120" />
      <el-table-column prop="action" label="操作" width="80" />
      <el-table-column prop="time" label="时间段" width="200" />
      <el-table-column prop="note" label="备注" width="200" />
      <el-table-column prop="default" label="默认应用" width="100">
        <template #default="{ row }">
          <el-switch v-model="row.default" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ $index }">
          <el-button type="primary" size="small" @click="editStrategy($index)">编辑</el-button>
          <el-button type="danger" size="small" @click="deleteStrategy($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogIndex === null ? '新增策略' : '编辑策略'" width="500px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="能源">
          <el-select v-model="form.energy" placeholder="请选择能源">
            <el-option label="电" value="电" />
            <el-option label="水" value="水" />
            <el-option label="气" value="气" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select v-model="form.device" placeholder="请选择设备">
            <el-option v-for="item in deviceMap[form.energy]" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作">
          <el-radio-group v-model="form.action">
            <el-radio label="开机" />
            <el-radio label="关机" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="时间段">
          <el-time-picker is-range v-model="form.timeRange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="note">
          <el-input v-model="form.note" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
        <el-form-item label="默认应用">
          <el-switch v-model="form.default" />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-switch v-model="form.enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStrategy">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
import { useRoute } from 'vue-router'
import { onMounted, watch } from 'vue'


const deviceOptions = computed(() => deviceMap[form.energy] || [])

const route = useRoute()

onMounted(() => {
  watch(
    () => route.query,
    (query) => {
      const { energy, device, note, auto } = query
      if (auto === 'true') {
        addStrategy()
        form.energy = energy || '电'
        form.device = device || ''
        form.note = note || ''
      }
    },
    { immediate: true }
  )
})


const dialogVisible = ref(false)
const dialogIndex = ref(null)
const searchKeyword = ref('')

const deviceMap = {
  电: ['空调', '照明', '电梯', '新风', '插座'],
  水: ['洗手间', '饮水机', '加湿器'],
  气: ['锅炉', '燃气灶', '热水器']
}


const energies = ['电', '水', '气']
const actions = ['开机', '关机']

const plans = ref([])
for (let i = 0; i < 10; i++) {
  const energy = energies[i % 3]
  const device = deviceMap[energy][Math.floor(Math.random() * deviceMap[energy].length)]
  const action = actions[i % 2]
  const startHour = 6 + (i % 10)
  const endHour = startHour + 1
  plans.value.push({
    energy,
    device,
    action,
    time: `${String(startHour).padStart(2, '0')}:00 - ${String(endHour).padStart(2, '0')}:00`,
    default: i % 3 === 0,
    enabled: i % 2 === 0
  })
}

const form = reactive({
  energy: '电',
  device: '',
  action: '开机',
  timeRange: [],
  default: false,
  enabled: true
})

const filteredPlans = computed(() => {
  return plans.value.filter(p =>
    !searchKeyword.value ||
    p.device.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

function addStrategy() {
  Object.assign(form, {
    energy: '电',
    device: '',
    action: '开机',
    timeRange: [],
    default: false,
    enabled: true
  })
  dialogIndex.value = null
  dialogVisible.value = true
}

function editStrategy(index) {
  const item = plans.value[index]
  const [start, end] = item.time.split(' - ')
  Object.assign(form, {
    energy: item.energy,
    device: item.device,
    action: item.action,
    timeRange: [start, end],
    default: item.default,
    enabled: item.enabled
  })
  dialogIndex.value = index
  dialogVisible.value = true
}

function saveStrategy() {
  const time = form.timeRange.join(' - ')
  const newItem = {
    energy: form.energy,
    device: form.device,
    action: form.action,
    time,
    default: form.default,
    enabled: form.enabled
  }
  if (dialogIndex.value === null) {
    plans.value.push(newItem)
    ElMessage.success('新增成功')
  } else {
    plans.value[dialogIndex.value] = newItem
    ElMessage.success('修改成功')
  }
  dialogVisible.value = false
}

function deleteStrategy(index) {
  plans.value.splice(index, 1)
  ElMessage.success('删除成功')
}

function exportExcel() {
  const rows = [['启用', '能源', '设备类型', '操作', '时间段', '默认应用']]
  for (const item of filteredPlans.value) {
    rows.push([item.enabled ? '是' : '否', item.energy, item.device, item.action, item.time, item.default ? '是' : '否'])
  }
  const ws = XLSX.utils.aoa_to_sheet(rows)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '调度策略')
  XLSX.writeFile(wb, '调度策略列表.xlsx')
}
</script>

<style scoped>
.plan-page {
  width: 100%;
  font-family: 'Microsoft Yahei', sans-serif;
}
</style>